package py.com.fms.session;

import java.util.*;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.*;


import py.com.fms.exception.CommonException;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.RolesBean;
import py.com.fms.fms.bean.UsersRolesBean;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.RolesServices;
import py.com.fms.fms.persistence.services.UsersRolesServices;


@SuppressWarnings("unused")
@Name("authenticator")
@Scope(ScopeType.SESSION)
public class Authenticator
{
    @Logger private Log log;

    @In Identity identity;
    @In Credentials credentials;
    
    boolean result = false;
    private ServiceSqlMap sqlMap;
    FacesMessages facesMessages;
    
    PasswordServices pwSrv;
    
    private UsersBean user;
    private UsersBean userData;
    private RolesBean roles;
    private Collection<RolesBean> userRoles;
    private UsersServices usSrv;
    private RolesServices rlSrv;
    private UsersRolesServices urSrv;
    
    public void initObjects() throws CommonException{
    	
    	if (sqlMap == null){
			sqlMap = new ServiceSqlMap();
		}
    	
    	if (facesMessages == null){
			facesMessages = new FacesMessages();
		}
    	
    	if(user == null){
    		user = new UsersBean();
    	}
    	
    	if(roles == null){
    		roles = new RolesBean();
    	}
    	
    	if(userRoles == null){
    		userRoles = new ArrayList<RolesBean>();
    	}
    	
    	if(userData == null){
    		userData = new UsersBean();
    	}
    	
    	if(usSrv == null){
    		usSrv = new UsersServices(this.sqlMap.getConfig());
    	}
    	
    	if(rlSrv == null){
    		rlSrv = new RolesServices(this.sqlMap.getConfig());
    	}
    	
    	if(urSrv == null){
    		urSrv = new UsersRolesServices(this.sqlMap.getConfig());
    	}
    	
    	if(pwSrv == null){
    		pwSrv = new PasswordServices();
    	}
    }
    
    public void initCredentials(){
    	if(credentials == null){
    		credentials = new Credentials();
    	}
    }
    
    public boolean login() throws CommonException{
//    	log.info("authenticating {0}", credentials.getUsername());
//        if ("admin".equals(credentials.getUsername()))
//        {
//            identity.addRole("admin");
//            return true;
//        }
//        return false;
    	if(this.getUserData() == null){
    		try{
    			 log.info("authenticating {0}", credentials.getUsername());
		        //write your authentication logic here,
		        //return true if the authentication was
		        //successful, false otherwise
    			 
    			// Initializing Objects
        		this.initObjects();
        		
        		// Setting User Parameters
            	this.getUser().setUserName(credentials.getUsername().toUpperCase());
            	this.getUser().setUserPass(pwSrv.encryptPass(credentials.getPassword().trim()));
            	
            	System.out.println("USER: " + this.getUser().getUserName());
            	System.out.println("PASS: " + this.getUser().getUserPass());
            	
            	// Getting User Data
            	this.setUserData(usSrv.getUserData(this.getUser()));       	
            	if (this.getUserData() == null) {
            		System.out.println("USER DATA: "+this.getUserData());
            		System.out.println("Usuario o password incorrecto");
            		FacesMessages.instance().add("Usuario o password incorrecto");
				} else {
					System.out.println("USER ID: " + this.getUserData().getId());

					if (this.getUserData() != null) {
						// Register User Roles
						this.setUserRoles(rlSrv.getUsersRoles(this.getUserData().getId()));

						for (RolesBean r : this.userRoles) {
							identity.addRole(r.getDescrip());
							System.out.println("ROLE: " + r.getDescrip());
						}
					}
				}
    		}catch(CommonException e){
    			e.printStackTrace();


    		}
		
    		
    	}
    	
    	result = (this.getUserData() == null ? false : true);
    	System.out.println("RESULT: " + this.result);
    	
    	String pass = credentials.getPassword();
    	this.initCredentials();
    	this.credentials.setInitialized(true);
    	this.credentials.setPassword(pass);
    	this.credentials.setUsername(this.getUser().getUserName());
//    	this.credentials.createCallbackHandler();
    	return result;
 	
       
    }

    
    // GETTERS AND SETTERS
	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}

	public UsersBean getUserData() {
		return userData;
	}

	public void setUserData(UsersBean userData) {
		this.userData = userData;
	}

	public RolesBean getRoles() {
		return roles;
	}

	public void setRoles(RolesBean roles) {
		this.roles = roles;
	}

	public Collection<RolesBean> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(Collection<RolesBean> userRoles) {
		this.userRoles = userRoles;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

}
